#!/bin/bash

if [[ $# -lt 1 ]]; then
   echo "Usage: $0 repo [pattern]"
   echo "  repo: path to the repo to dump"
   echo "  pattern: optional, specifies an sql 'like' pattern to match paths"
   exit 1
fi

repo=$1
pattern=$2

if [[ -n $DUMP_HHAS ]] ; then
    dump_what=-vEval.DumpHhas="${DUMP_LEVEL:-1}"
else
    dump_what=-vEval.DumpBytecode="${DUMP_LEVEL:-1}"
fi

table=$(sqlite3 "$repo" ".tables 'FileSha1%'")
where=
if [[ -n $pattern ]] ; then
   where="WHERE path like '$pattern'"
fi
sqlite3 "$repo" "select path from $table $where" | \
   grep -v "^/:" | \
   xargs -I% sh -c \
        "echo ==== Dumping % ======; \
         ${HHVM:-hhvm} -vRepo.Authoritative=true -vRepo.Path=$repo $dump_what --lint=% 2>&1 | \
         grep -v '^No syntax errors detected in'; \
         echo"
